var MAX_PRICE = 1000000000000;
var MIN_PRICE = 10000;
var UPLOAD_SUCCESS = 1;
var UPLOAD_FAIL = 2;
var MSG_UPLOAD_FAIL = "Bạn chỉ được sử dụng tập tin hình ảnh.";
var MSG_UPLOAD_ERROR = "Đăng ảnh không thành công vui lòng thử lại.";
var MSG_DELETE_ERROR = "Xóa ảnh không thành công vui lòng thử lại.";
var CAT_ID = ",1,2,3,4,5,6,7,8,";

$(document).ready(function() {
	
	$(document).on('change', '.postImage', function(e){
		index = $(this).attr('class').match(/\d+/)[0];
    	prepareUpload($(this),index);
    	
    });
    $(document).on('click','.remove-image',function(){
    	$img = $(this).closest('div.image-up-success').find('img');
    	index = $(this).attr('class').match(/\d+/)[0];
    	deleteImage($img.attr('src'),$(this),index);
    	
    });
    validateForm($("#stallsPosting"));
    addCustomRule();
    initRules();
    
    $('#data_price').autoNumeric('init');
    //option
    $(document).on('change','#data_option1',function(){
    	val = eval($(this).val());
    	if(val == 0){
    		$("#data_option2").prop("disabled",false);
    		/*$('#data_option2').rules("add", {
         	  	required : true
      		});*/
    	}else{
    		$("#data_option2").prop("disabled",true);
    		//$("#data_option2").rules( "remove" );
    	}
    });
    
	
    
    // hide 4 row
    $(document).on("change","#data_category_id",function(){
    	val = ","+$("#data_category_id").val()+",";
    	hideForklift(val);
    });
    _val = ","+$("#data_category_id").val()+",";
    	hideForklift(_val);
  
    var vals = $("#data_option1").val();
	if(vals == 0){
		$("#data_option2").prop("disabled",false);
		/*$('#data_option2').rules("add", {
     	  	required : true
  		});*/
	}else{
		$("#data_option2").prop("disabled",true);
		console.log("gfgfd");
		//$("#data_option2").rules( "remove" );
	}
});
function prepareUpload($input,index){
    files = $input.prop('files');
    var fd = new FormData();
    fd.append("image", files[0]);
    $.ajax({
        url : "/StallsPosting/uploadImage",
        type : "POST",
        data : fd,
        contentType: false,
        processData:false,
        beforeSend: function(){
			//console.log("beforeSend");
		},
		success: function(data){
			jsonData = JSON.parse(data);
			if(jsonData.success == UPLOAD_SUCCESS){
				//console.log(jsonData.path);
				updateSrcImage($input.closest('div').find('.image-up-success'),jsonData.path, index);
			}else{
				showPopupMessage('#myModal',MSG_UPLOAD_FAIL);
			}
		},
		error: function(error){
			showPopupMessage('#myModal',MSG_UPLOAD_FAIL);
		}
    });
}
function updateSrcImage($img, path, index){
	$img.css('display','block');
	$img.find("img").prop('src','/'+path);
	$('.img_'+index).val(path);
	$('.img'+index).val("");
	
}
function deleteImage(srcFile, $btn, index){
	$.ajax({
        url : "/StallsPosting/deleteImage",
        type : "POST",
        dataType : "json",
        data : {
            "src" : srcFile
        },
        beforeSend: function(){
			
		},
		success: function(data){
			$btn.closest("div.image-up-success").css('display','none');
			$btn.closest("div.image-up-success").find('img').attr('src','');
			$('.img_'+index).val("");
		},
		error: function(error){
			showPopupMessage('#myModal',MSG_UPLOAD_ERROR);
		}
    });
}
function showPopupMessage(idModal, msg){
	$(idModal).find('.modal-body').html(msg);
	$(idModal).modal('show');
}
/**
 *validate 
 */
function validateForm($form){
	$form.validate({
		ignore: "",
        onfocusout : function( element, event ) {
		    if ($(element).valid()){
        		$(element).closest('div.posting_row').find('.category_group_warntip').removeClass("show");
		    	$(element).closest('div.posting_row').find('.category_group_warntip').addClass("hide");
		    }
		},
        onkeyup: function( element, event ) {
		    $(element).valid();
		},
		
        errorPlacement: function (error, element) {
            $(element).closest('div.posting_row').find('.category_group_warntip').removeClass("hide");
            $(element).closest('div.posting_row').find('.category_group_warntip').addClass("show");
        },
        invalidHandler: function(form, validator) {
            if (!validator.numberOfInvalids()){
                return;
            }
            scrollToTopElement($(validator.errorList[0].element));
        }
    });
    
}
function initRules(){
	$('#data_product_name').rules("add", {
            required : true,
            minlength: 2,
      });
    $('#data_category_id').rules("add", {
            validateSelect : "0"
     });
    $('#data_price').rules("add", {
            required : true,
            checkRange: true
    });
    $("#data_product_year").rules("add", {
            required : true,
            number: true
    });
    $("#data_manufacturer").rules("add", {
            required : true
    });
    $("#data_model").rules("add", {
            required : true
    });
    $("#data_time_used").rules("add", {
            required : true,
            number: true
    });
    $(".postImage").rules("add", {
            requireImg : true,
    });
    $("#data_work_weight").rules("add", {
            required : true,
            validateRangeValue: [0,100000]
    });
    $("#data_height").rules("add", {
            required : true,
            validateRangeValue: [0,100000]
    });
    $("#data_weight").rules("add", {
            required : true,
            validateRangeValue: [0,100000]
    });
    //validateRequireOne
    
    $("#best_sell").rules("add", {
            validateRequireOne : true,
    });
    $("#product_new").rules("add", {
            validateRequireOne : true,
    });
}
function scrollToTopElement($element){
	if($element.hasClass('postImage')){
		$element = $('.element-images');
	}
	//posting_element
    $('html, body').animate({
        scrollTop: $element.offset().top
    }, 100);
}
/**
 * add rule
 */
 function addCustomRule(){
 	 $.validator.addMethod('validateSelect', function (value, element, arg) {
        return arg != value;
    }, 'Vui lòng chọn');
    $.validator.addMethod('requireImg', function (value, element, arg) {
        var n = 0;
		$(".hdImg").each(function(){
		  if($(this).val()!=""){
		     n++;
		  }
		});
		return n > 0;
    }, 'Vui lòng chọn');
    $.validator.addMethod('checkRange', function (value, element, arg) {
    	value = value.split(".");
    	if(value.length>0){
    		value = value[0];
    	}
    	value = value.replace(/[.,]/g, '');
    	if(isNaN(value)){
    		return false;
    	}
    	value = eval(value);
    	return value > MIN_PRICE && value < MAX_PRICE;
    	
    },'Nhập số');
    $.validator.addMethod('validateRangeValue', function (value, element, arg) {
    	return checkRangeValue(value, arg[0], arg[1]);
    },'Nhập số');
    
    $.validator.addMethod('validateRequireOne', function (value, element, arg) {
    	return rulerequireOne();
    },'Vui lòng chọn');
    
    $.validator.addMethod('validateCheckNumber', function (value, element, arg) {
    	return checkNumber(value);
    },'Vui lòng nhập số');
    
 }
 function remmoveRuleValidate(){
 	$("#data_work_weight").rules( "remove" );
 	$("#data_height").rules( "remove" );
 	$("#data_weight").rules( "remove" );
 }
 function addRuleValidate(){
 	$("#data_work_weight").rules("add", {
            required : true,
            validateRangeValue: [0,100000]
    });
    $("#data_height").rules("add", {
            required : true,
            validateRangeValue: [0,100000]
    });
    $("#data_weight").rules("add", {
            required : true,
            validateRangeValue: [0,100000]
    });
 }
//------------ function
function checkRangeValue(value, minValue, maxValue){
	//if(! /^\d+$/.test(value)){
	if(!/^[0-9]*\.?[0-9]*$/.test(value)){
		return false;
	}
	value = eval(value);
	return value > minValue && value < maxValue;
}
function hideForklift(_val){
	if(CAT_ID.indexOf(_val)>-1){
    		$(".forklift").removeClass("hide");
    		addRuleValidate();
    		$(".forklift").find("input,select").prop("disabled",false);
    	}
    	else{
    		$(".forklift").addClass("hide");
    		remmoveRuleValidate();
    		$(".forklift").find("input,select").prop("disabled",true);
    	}
}
function rulerequireOne(){
	n = $(".typeProduct").find("input[type='checkbox']:checked").size();
	return n > 0;
}
function checkNumber(val){
	return $.isNumeric(val);
} 
